<template>
  <ContainerGroup>
    <Container style="margin-bottom:10px">
      <FilterForm :elements="queryForm" @reset="reset" @submit="handleSearch" />
    </Container>
    <!-- 查询 -->

    <Container height="fill" display="flexY">
      <OperationContainer class="button-bar">
        <Button icon="add" @click="addDetail">新增</Button>
        <Button type="info" @click="handleJc">继承</Button>
      </OperationContainer>
      <!-- 表格 -->
      <div class="table-box">
        <el-table
          v-loading="tableLoading"
          :data="ruleDetail"
          default-expand-all
          height="100%"
          border
          :header-cell-style="{
            background: '#fafafa',
            borderColor: '#e7ecf8',
          }"
          row-key="code"
        >
          <!-- <el-table-column align="center" type="selection" width="55" /> -->
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column prop="extendField1" label="年" />
          <el-table-column prop="extendField2" label="月" />
          <!-- <el-table-column prop="deptcode" label="科室编号" /> -->
          <el-table-column label="科室编号" prop="deptcode">
          <!-- <template slot-scope="scope">
            <div class="text-btn">
              {{
                scope.row.deptcode === "AAAAAAAAAA"
                  ? "9999"
                  : scope.row.deptcode
              }}
            </div>
          </template> -->
          </el-table-column>
          <el-table-column prop="deptname" label="科室名称" />
          <el-table-column prop="todeptcode" label="部门编号" />
          <el-table-column prop="todeptname" label="部门名称" />
          <el-table-column prop="rulecode" label="床位系数" />
          <!-- <el-table-column prop="updatedOn" label="操作时间" width="180" /> -->
          <!-- <el-table-column align="center" label="是否启用" width="120">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.rowStatus"
                active-color="#FFA712"
                :active-value="'0'"
                :inactive-value="'1'"
                @change="switchUse(scope.row)"
              />
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <!-- <span class="edit-detail" @click="editDetail(scope.row)">修改</span> -->
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <i
                  class="el-icon-edit-outline"
                  style="
                      padding-top: 4px;
                      font-size: 20px;
                      color: #207efa;
                      cursor: pointer;
                    "
                  @click="editDetail(scope.row)"
                />
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="top"
                style="margin-left: 10px"
              >
                <i
                  class="el-icon-delete"
                  style="
                      padding-top: 4px;
                      font-size: 20px;
                      color: #207efa;
                      cursor: pointer;
                    "
                  @click="handleDel(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <!-- <Pagination
          :total="pageAttr.total"
          :page="pageAttr.currentPage"
          :page-size="pageAttr.pageSize"
          @pagation="pagationChange"
        /> -->
      <!-- 对话框区域开始 -->
      <Dialog
        :title="dialogTitle"
        :visible="dialogVisible"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '关闭',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @confirm="dialogCommit"
        @cancel="dialogClose"
      >
        <el-form ref="form" :model="form" label-width="120px" size="small">
          <el-form-item label="年月:">
            <el-date-picker
              v-model="form.yearMonth"
              clearable
              size="small"
              type="month"
              placeholder="请选择年月"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :picker-options="expireTimeOptionBm"
              :disabled="isEdit"
            />
          </el-form-item>
          <el-form-item label="科室名称：">
            <el-select v-model="form.originDept" clearable filterable :disabled="isUpdate">
              <template v-for="(item, index) in deptType">
                <el-option
                  :key="index"
                  :value="item.deptCode + '/' + item.deptName"
                  :label="item.deptName"
                />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="部门：">
            <el-select v-model="form.targetDept" clearable filterable>
              <template v-for="(item, index) in deptType">
                <el-option
                  :key="index"
                  :value="item.deptCode + '/' + item.deptName"
                  :label="item.deptName"
                />
              </template>
            </el-select>
          </el-form-item>
          <el-form-item label="床位系数：">
            <el-input
              v-model="form.flowInShare"
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
      </Dialog>
      <!-- 继承 -->
      <Dialog
        title="继承"
        :visible="jcVisable"
        :footer-btns="[
          {
            text: '确定',
            type: 'primary',
            trigger: 'confirm',
          },
          {
            text: '关闭',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @confirm="handleSaveJc"
        @cancel="jcVisable = false"
      >
        <el-form ref="form" label-width="80px">
          <el-form-item label="源年月:">
            <el-date-picker
              v-model="ruleName"
              clearable
              size="small"
              type="month"
              placeholder="请选择年月"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :picker-options="expireTimeOptionBm"
            />
          </el-form-item>
          <el-form-item label="目标年月:">
            <el-date-picker
              v-model="mbYm"
              clearable
              size="small"
              type="month"
              placeholder="请选择年月"
              format="yyyy-MM"
              value-format="yyyy-MM"
              :picker-options="expireTimeOptionBm"
            />
          </el-form-item>
        </el-form>
      </Dialog>
    </Container>
  </ContainerGroup>
</template>

<script>
import TimeSelector from './children/TimeSelector.vue'
import {
  addRuleCompelamortization,
  getDepartmentSource,
  getCompelAmortization,
  deleteCompelAmortization,
  updateCompelamortization,
  getRuleCompelAmortizationById,
  insertBatchRuleCompelAmortization
} from '../../../utils/apis/accountingUnit/share.js'
import { Force } from '../../../utils/force'
import { ShareParams } from '../../../utils/shareParams'
import { FlowInShare } from '../../../utils/flowInShare'
export default {
  name: 'Force', // 强制分摊
  components: {
    // eslint-disable-next-line vue/no-unused-components
    TimeSelector
  },
  data() {
    const _this = this
    return {
      expireTimeOptionBm: {
        disabledDate(date) {
          // disabledDate 文档上：设置禁用状态，参数为当前日期，要求返回 Boolean
          return (
            date.getTime() > new Date(_this.$util.currentDate(2)).getTime()
          )
        }
      },
      tableLoading: false,
      newParamList: {},
      ruleList: [],
      ruleName: _this.$util.currentDate(2),
      mbYm: _this.$util.currentDate(1),
      jcVisable: false,
      isUpdate: false,
      rowId: '',
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      height: 'fill',
      queryForm: [
        // {
        //   clearable: true,
        //   value: "",
        //   remote: true,
        //   remoteMethod: this.unitFilter,
        //   itemLabel: "code",
        //   itemValue: "value",
        //   label: "年月",
        //   key: "yearMonth",
        //   type: "Select",
        //   options: [],
        // },
        {
          key: 'yearMonth',
          label: '年/月',
          mode: 'month',
          type: 'date-picker',
          format: 'yyyy-MM',
          value: this.$util.currentDate(),
          width: 210,
          defaultValue: this.$util.currentDate()
        }
      ],
      // 会计分类
      deptType: [],
      apportionType: [],
      // 规则详情表单
      ruleDetail: [],
      isEdit: false,
      showEidtVlidate: false,
      drawerTitle: '',
      dialogTitle: '',
      dialogVisible: false,
      form: {
        originDept: '',
        targetDept: '',
        flowInShare: '',
        yearMonth: this.$util.currentDate(1)
      },
      dialogTitle2: '',
      dialogVisible2: false,
      objectNameList: [
        {
          name: '对象1',
          value: '1'
        },
        {
          name: '对象2',
          value: '2'
        },
        {
          name: '对象3',
          value: '3'
        },
        {
          name: '对象4',
          value: '4'
        }
      ],
      deptList: [
        {
          name: '骨科',
          value: '1'
        },
        {
          name: '呼吸科',
          value: '2'
        },
        {
          name: '耳鼻喉科',
          value: '3'
        },
        {
          name: '外科',
          value: '4'
        }
      ]
    }
  },
  created() {},
  mounted() {
    // this.getinitYM();
    this.getinit()
  },
  methods: {
    handleSearch(value) {
      this.newParamList = value
      this.getData()
    },
    handleSaveJc() {
      if (!this.ruleName) {
        this.$message.warning('请选择源年月')
        return
      }
      if (!this.mbYm) {
        this.$message.warning('请选择目标年月')
        return
      }
      const flowInShare = new FlowInShare()
      flowInShare.yearSource = this.ruleName.split('-')[0]
      flowInShare.monthSource = this.ruleName.split('-')[1]
      flowInShare.yearTarget = this.mbYm.split('-')[0]
      flowInShare.monthTarget = this.mbYm.split('-')[1]
      insertBatchRuleCompelAmortization(flowInShare).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData()
          this.jcVisable = false
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleCancleJc() {
      this.jcVisable = false
    },
    handleJc() {
      // 继承
      this.ruleName = this.$util.currentDate(2)
      this.mbYm = this.$util.currentDate(1)
      this.jcVisable = true
    },
    getinitYM() {
      // getRuleCompelamortizationYearMonth().then((res) => {
      //   if (res.data.code === 200) {
      //     this.queryForm[0].options = res.data.data;
      //     this.ruleList = res.data.data;
      //     this.$nextTick(() => {
      //       this.queryForm[0].value = res.data.data[0].value;
      //       // this.getData()
      //     });
      //   }
      // });
    },
    handleDel(row) {
      // 删除
      // if (this.selectionCBox.length === 0) {
      //   this.$message.error("请选择删除的数据");
      // } else {
      const ids = [row.id]
      // this.selectionCBox.map((item) => {
      //   ids.push(item.id);
      // });

      this.$confirm({
        title: '温馨提示',
        content: '您确定要删除该条数据?',
        okText: '确定',
        cancelText: '取消',
        okFn: () => {
          deleteCompelAmortization(ids).then((res) => {
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.getData()
            } else {
              this.$message.error(res.data.message)
            }
          })
        },
        cancelFn: () => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      })

      // }
    },
    getinit() {
      getDepartmentSource({
        projectId: '1',
        SysId: 'Cost'
      }).then((res) => {
        if (res.data.code === 200) {
          this.deptType = res.data.data
        }
      })
    },
    // 新增
    dialogCommit() {
      if (!this.form.originDept) {
        this.$message.warning('请选择科室名称')
        return
      }
      if (!this.form.targetDept) {
        this.$message.warning('请选择部门')
        return
      }
      const force = new Force()
      force.deptcode = this.form.originDept.split('/')[0]
      force.deptname = this.form.originDept.split('/')[1]
      force.todeptcode = this.form.targetDept.split('/')[0]
      force.todeptname = this.form.targetDept.split('/')[1]
      force.yearTarget = this.form.yearMonth.split('-')[0]
      force.monthTarget = this.form.yearMonth.split('-')[1]
      force.rulecode = this.form.flowInShare

      if (this.dialogTitle === '新增') {
        addRuleCompelamortization(force).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        force.id = this.rowId
        updateCompelamortization(force).then((res) => {
          if (res.data.code === 200) {
            this.$message.success(res.data.message)
            this.getData()
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },
    getData(val) {
      const force = new Force()

      // force.yearMonth = this.newParamList.yearMonth;
      force.yearTarget = this.newParamList.yearMonth.split('-')[0]

      force.monthTarget = this.newParamList.yearMonth.split('-')[1]

      // force.pageIndex = this.pageAttr.currentPage;
      // force.pageSize = this.pageAttr.pageSize;
      this.tableLoading = true
      this.ruleDetail = []
      getCompelAmortization(force).then((res) => {
        this.tableLoading = false
        if (res.data.code === 200) {
          this.ruleDetail = res.data.data
          // this.pageAttr.total = res.data.data.total || 0;
        }
      })
    },
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData()
    },
    stopDefault(e) {
      e.stopPropagation()
    },
    rowClick(row) {
      // 点击row 获取code 请求接口
      const word = row.word
      this.ruleDetail = this.tableData[word]
    },
    // addDetail() {
    //   this.showDetail()
    // },
    editDetail(row) {
      // this.form.originDept = row.deptcode + "/" + row.deptname;
      // this.form.targetDept = row.deptcode + "/" + row.deptname;
      this.form.flowInShare = row.rulecode
      this.rowId = row.id
      this.isUpdate = true
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.isEdit = true
      this.showDetail(row)
    },
    showDetail(row) {
      const shareParams = new ShareParams()
      this.showEidtVlidate = true
      if (this.dialogTitle === '编辑') {
        this.drawerTitle = '修改核算单元'
        shareParams.id = row.id
        getRuleCompelAmortizationById(shareParams).then((res) => {
          if (res.data.code === 200) {
            this.form.originDept =
              res.data.data.deptcode + '/' + res.data.data.deptname
            this.form.targetDept =
              res.data.data.todeptcode + '/' + res.data.data.todeptname
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        this.drawerTitle = '新增核算单元'
      }
    },
    switchUse(row) {
      const force = new Force()
      force.id = row.id
      force.rowStatus = row.rowStatus
      updateCompelamortization(force).then((res) => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message)
          this.getData()
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 向FilterForm中的Select-Options追加选项
    addSeletOption(label, opts) {
      this.queryForm.map((item) => {
        if (item.label === label) {
          item.options = opts
        }
      })
    },
    setDefault(row) {
      // console.log(row);
    },
    reset() {
      this.pageAttr.currentPage = 1
    },
    drawClose() {
      this.showEidtVlidate = false
    },
    saveEidtRule() {
      // console.log("saveEidtRule");
    },
    getTypeByTime(time) {
      // console.log(time);
    },
    addDetail() {
      this.form.originDept = ''
      this.form.targetDept = ''
      this.form.flowInShare = ''
      this.isUpdate = false
      this.dialogTitle = '新增'
      this.showDialog()
    },
    showDialog(row) {
      this.dialogVisible = true
    },
    dialogClose() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },

    addRule() {
      this.dialogTitle2 = '添加规则'
      this.dialogVisible2 = true
    },
    dialogClose2() {
      this.dialogVisible2 = false
      this.$refs.form2.resetFields()
    },
    dialogCommit2() {
      this.dialogVisible2 = false
      this.$refs.form2.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.dept-type {
  padding: 0 !important;
  flex: 0 0 240px;
  margin-right: 10px;
}
.time-box {
  flex: 0 0 240px;
  display: flex;
  flex-direction: column;
  .title {
    flex: 0;
    background-color: #fcfcfc;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .outside {
    flex: 1;
  }
}
.rule-detail {
  padding: 0 !important;
  flex: 1;
}
.title {
  box-sizing: border-box;
  padding: 10px;
  width: 100%;
  background-color: #fefefe;
  border-bottom: 1px solid #e8eaed;
}
.edit-detail {
  color: #4073ff;
  cursor: pointer;
}
.button-bar {
  height: 48px;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 12px;
  // border-bottom: 1px solid #ccc;
  button {
    margin-left: 12px;
  }
  button:first-of-type {
    margin-left: 0;
  }
}
.is-child {
  display: inline-block;
  padding-left: 12px;
}
.not-child {
  font-weight: bold;
}
.table-box {
 flex: 1;
}
.query-form {
  // border-bottom: 1px solid #ccc;
  button {
    margin-left: 12px;
  }
}
.is-default {
  color: #4073ff;
  cursor: pointer;
}
.query-box {
  flex: 1;
}
/deep/ .el-select {
  width: 100%;
}
</style>
